import tkinter as tk
from tkinter import scrolledtext
import requests
import json
import os


class DeepSeekAPI:
    def __init__(self, api_key):  #
        self.api_key = api_key
        self.base_url = "https://api.deepseek.com/v1"  # 请确认实际API地址

    def chat_completion(self, messages, model="deepseek-chat", temperature=0.7, max_tokens=2000):
        """
        调用DeepSeek的对话API

        参数:
            messages: 对话消息列表，格式如 [{"role": "user", "content": "你好"}]
            model: 使用的模型名称
            temperature: 生成文本的随机性
            max_tokens: 生成的最大token数

        返回:
            API的响应结果
        """
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

        payload = {
            "model": model,
            "messages": messages,
            # "stream": True,  # 关键：启用流式传输
            "temperature": temperature,
            "max_tokens": max_tokens
        }

        try:
            response = requests.post(
                f"{self.base_url}/chat/completions",
                headers=headers,
                data=json.dumps(payload)
            )
            response.raise_for_status()  # 检查请求是否成功
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {e}")
            return None


class DeepseekQueryApp:
    def __init__(self, master):
        self.master = master
        master.title("苏鹏开发的DeepSeek系统")

        # # 创建一个标签，用于说明输入框用途
        # self.label_question = tk.Label(master, text="请输入您的问题:")
        # self.label_question.pack()

        # 上面的文本框，用来输入问题
        self.text_question = tk.Text(master, height=15, width=80)
        # 添加初始提示文本
        self.text_question.insert("1.0", "请帮我解决如下提问：\n")
        self.text_question.config(fg="gray")  # 设置提示文本为灰色
        self.text_question.pack()

        # 执行提问的按钮
        self.button_query = tk.Button(master, text="使用苏鹏开发的DeepSeek软件回答", command=self.send_query)
        self.button_query.pack()

        # # 下面的文本框，用来显示回复信息
        # self.label_response = tk.Label(master, text="查询结果:")
        # self.label_response.pack()

        self.text_response = scrolledtext.ScrolledText(master, height=25, width=80)
        self.text_response.insert("1.0", "这里将显示答案，请等待......：\n")
        self.text_response.config(fg="gray")  # 设置提示文本为灰色
        self.text_response.pack()

    def send_query(self):
        # 获取输入的问题
        # self.text_response.delete("1.0", tk.END)  # 清空回复框
        # self.text_response.insert(tk.END, response_text + "\n")
        question = self.text_question.get("1.0", tk.END).strip()

        if not question:
            self.text_response.insert(tk.END, "请输入一个问题。\n")
            return

        # 初始化response为默认值

        response_text = "无法获取回答"

        try:
            # 替换为你的实际API密钥

            API_KEY=os.getenv("DEEPSEEK_API_KEY")
            if not API_KEY:
                raise ValueError("未设置环境变量 DEEPSEEK_API_KEY")

            deepseek = DeepSeekAPI(API_KEY)

            # 构造对话消息，使用用户输入的问题
            messages = [
                {"role": "user", "content": question}
            ]

            # 调用API
            response = deepseek.chat_completion(messages)

            if response and "choices" in response and len(response["choices"]) > 0:
                response_text = response["choices"][0]["message"]["content"]
            else:
                response_text = "API调用失败或未返回有效数据"

        except Exception as e:
            response_text = f"发生错误: {str(e)}"

        # 显示回复信息
        self.text_response.insert(tk.END, response_text + "\n")


if __name__ == "__main__":
    root = tk.Tk()
    root.resizable(False, False)
    app = DeepseekQueryApp(root)
    root.mainloop()